#coding:utf-8
import math
from django.db.models import Count
from lovewith.settings import PAGE_SIZE
from lovewith.share.views.modules.attach import AttachApi
from lovewith.supplier.models import Supplier, ServiceCate, SupplierServiceType, SupplierServiceArea
from lovewith.utils.mtcache import MtCache
from lovewith.utils.tools import my_iterator
from lovewith.website.views.modules.province import ProvinceApi


class SupplierApi:
    def __init__(self):
        pass

    @staticmethod
    def check_data(user_id=None, supplier_id=None):
        supplier_filter_data = None
        if user_id:
            supplier_filter_data = Supplier.objects.filter(user_id=int(user_id))
        if supplier_id:
            supplier_filter_data = Supplier.objects.filter(id=int(supplier_id))

        if supplier_filter_data.exists():
            return supplier_filter_data[0]
        else:
            return None

    #验证服务分类是否合法
    @staticmethod
    def check_service_cate(cate_id):
        cate_data = ServiceCate.objects.filter(id=int(cate_id))
        if cate_data.exists():
            return cate_data[0]
        else:
            return None

    #获取全部服务分类
    @staticmethod
    def get_service_cate():
        service_cate = MtCache('supplier_service_cate').get()

        if not service_cate:
            service_cate = []

            service_filter_cate = ServiceCate.objects.all().order_by('-sort')
            for cate in service_filter_cate:
                service_cate.append({
                    'id': cate.id,
                    'name': cate.name
                })

            MtCache('supplier_service_cate').set(service_cate)

        return service_cate

    #服务商服务类型
    @staticmethod
    def get_service_type(supplier_id, service_id=None):
        if not service_id:
            return SupplierServiceType.objects.filter(supplier_id=int(supplier_id))
        else:
            service_filter_data = SupplierServiceType.objects.filter(supplier_id=int(supplier_id),
                                                                     service_id=int(service_id))
            if service_filter_data.exists():
                return service_filter_data[0]
            return None

    #服务商服务范围
    @staticmethod
    def get_service_area(supplier_id):
        return SupplierServiceArea.objects.filter(supplier_id=int(supplier_id))

    #增加服务商
    @staticmethod
    def add_supplier(**kwargs):
        new_supplier = Supplier(**kwargs)
        new_supplier.save()

        return new_supplier

    #添加服务商服务
    def upate_supplier_service(self, supplier, serivice_ids):
        new_service = []

        #删除历史数据
        SupplierServiceType.objects.filter(supplier_id=supplier.id).delete()

        for sid in serivice_ids:
            service_data = self.check_service_cate(int(sid))
            if service_data:
                new_service.append(SupplierServiceType(supplier=supplier, service=service_data, user=supplier.user))

        SupplierServiceType.objects.bulk_create(new_service)

    #更新服务商服务范围
    @staticmethod
    def upate_supplier_area(supplier, area_ids):
        new_area = []
        #删除历史数据
        SupplierServiceArea.objects.filter(supplier_id=supplier.id).delete()

        for city_id in area_ids:
            city_data = ProvinceApi.check_data(cid=int(city_id))
            if city_data:
                new_area.append(SupplierServiceArea(city=city_data, supplier=supplier, user=supplier.user))

        SupplierServiceArea.objects.bulk_create(new_area)

    #服务商列表
    @staticmethod
    def get_suppliers_post(city_id='all', page_no=1, service_id='all'):
        supplier_post_data = MtCache('supplier_list').get(city_id=city_id, page=page_no, service_id=service_id)

        if not supplier_post_data:
            start = (page_no - 1) * PAGE_SIZE
            last = page_no * PAGE_SIZE

            if not service_id or service_id == 'all':
                if city_id == 'all':
                    all_supplier_data = SupplierServiceArea.objects.values('supplier').annotate(
                        dcount=Count('supplier')).order_by('-supplier__score')
                else:
                    all_supplier_data = SupplierServiceArea.objects.values('supplier').annotate(
                        dcount=Count('supplier')).filter(city_id=int(city_id)).order_by('-supplier__score')
            else:
                if city_id == 'all':
                    all_supplier_data = Supplier.objects.values('id').annotate(
                        dcount=Count('user')).filter(ServiceType__service=int(service_id)).order_by('-score')
                else:
                    all_supplier_data = Supplier.objects.values('id').annotate(dcount=Count('id')).filter(
                        ServiceType__service=int(service_id), ServiceArea__city=int(city_id)).order_by('-score')

            if last > all_supplier_data.count():
                last = all_supplier_data.count()

            #总页数
            total_page = int(math.ceil(all_supplier_data.count() / PAGE_SIZE))
            total_page = 1 and total_page or 1

            all_supplier_post = []
            supplier_data = all_supplier_data[start: last]
            for su in my_iterator(supplier_data):
                the_supplier_data = None
                if 'supplier' in su:
                    the_supplier_data = SupplierApi.check_data(supplier_id=int(su['supplier']))
                else:
                    the_supplier_data = SupplierApi.check_data(supplier_id=int(su['id']))

                if the_supplier_data and the_supplier_data.enable == 1:
                    user_data = the_supplier_data.user
                    the_supplier_post = {}
                    share_post = AttachApi.get_new_post_cover_by_user(user_data.id)

                    for i in range(len(share_post)):
                        the_supplier_post['cover_%s' % i] = {
                            'share_id': share_post[i].share_post_id,
                            'title': share_post[i].share_post.title or '',
                            'path': share_post[i].path or ''
                        }

                    the_supplier_post['uid'] = user_data.id
                    the_supplier_post['username'] = the_supplier_data.company
                    the_supplier_post['avatar'] = user_data.avatar

                    all_supplier_post.append(the_supplier_post)

            supplier_post_data = {
                'current_page': page_no,
                'total_page': total_page,
                'data': all_supplier_post
            }

            MtCache('supplier_list').set(supplier_post_data, city_id=city_id, page=page_no, service_id=service_id)

        return supplier_post_data

    #根据图片服务类型获取服务商列表
    @staticmethod
    def get_by_image(service_type_id, city_id):
        supplier_data = Supplier.objects.values('id').annotate(dcount=Count('id')).filter(
            ServiceType__service__in=service_type_id, ServiceArea__city=int(city_id)).order_by('id')
        return supplier_data[0:6]
